import pymysql

class HeiMa(object):
    def __init__(self):
        self.conn = pymysql.connect(host = "192.168.199.132", port = 3306, user = "root", password = "mysql", db = "heima", charset = "utf8")

    def show_info(self):
        print("1.添加学生")
        print("2.查询学生")
        print("3.退出程序")

    def add(self):
        '''添加用户'''
        while True:
            cur = self.conn.cursor()
            user_name = input("请输入你的姓名：")
            cur.execute("select name from users group by name")
            res = cur.fetchall()
            cur.close()
            if (user_name,) in res:
                print("该用户名已存在，请重新添加")
                continue
            user_age = input("请输入你的年龄:")
            try:
                user_age_int = int(user_age)
                if user_age_int > 0 and user_age_int < 150:
                    pass
                else:
                    print("你输入你的年龄不和规范")
                    continue
            except:
                print("你输入你的年龄不和规范,应为大于0的整数")
                continue
            user_sex = input("请输入你的性别：")
            if user_sex != "男" and user_sex != "女":
                print("请输入正确格式：男或者女")
                continue
            user_phone = input("请输入你的电话号码：")

            if len(user_phone) == 11 and user_phone.isdigit():
                pass
                break
            else:
                print("格式不对，请重新输入。")
                continue
        cur = self.conn.cursor()
        cur.execute("insert into users values (%s,%s,%s,%s,%s)",[0,user_name,user_age,user_sex,user_phone])
        self.conn.commit()
        cur.close()


    def select(self):
        '''查询用户'''
        cur = self.conn.cursor()
        user_name = input("请输入你要查询的姓名：")
        try:
            cur.execute("select * from users where name = %s",[user_name])
        except:
            print("查询失败。")
        else:
            print(cur.fetchall())

    def main(self):
        while True:
            self.show_info()
            user_info = input("请输入你要进行的操作：")
            if user_info == "1":
                self.add()
            elif user_info == "2":
                self.select()
            elif user_info == "3":
                print("欢迎下次使用。")
                break
            else:
                print("请输入有效编号。")
                continue

if __name__ == '__main__':
    heima = HeiMa()
    heima.main()